package action;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import model.CartModel;
import model.ProductCartDetail;
import model.ProductModel;

import org.apache.log4j.Logger;
import org.apache.struts2.interceptor.RequestAware;
import org.apache.struts2.interceptor.SessionAware;
import org.springframework.beans.factory.annotation.Autowired;

import pojo.Carrier;
import pojo.Category;
import pojo.CustomerReview;
import pojo.DeviceBrand;
import pojo.OperatingSystem;
import pojo.Overview;
import pojo.Price;
import pojo.Product;
import pojo.ProductImage;
import service.Tools;

import com.opensymphony.xwork2.ActionSupport;

import dao.CategoryDAO;
import dao.DeviceBrandDAO;
import dao.PriceDAO;
import dao.ProductDAO;
import dao.CarrierDAO;
import dao.OperatingSystemDAO;
import dao.CustomerReviewDAO;

public class CategoryAction extends ActionSupport implements RequestAware, SessionAware{
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 8000848192880948922L;

	private static final Logger logger = Logger.getLogger(CategoryAction.class);
	
	private Map<String, Object> request;
    private Map<String, Object> session;
    
    private String idCategory;
    
    private String keySearch;

	@Autowired
	private CategoryDAO CategoryDAO;
    
    @Autowired
	private ProductDAO ProductDAO;
    
    @Autowired
	private PriceDAO PriceDAO;
    
    @Autowired
	private DeviceBrandDAO DeviceBrandDAO;

    @Autowired
	private CarrierDAO CarrierDAO;
    
    @Autowired
	private OperatingSystemDAO OperatingSystemDAO;
    
    @Autowired
	private CustomerReviewDAO CustomerReviewDAO;
    
    private String sku = "";
	public void setSku(String sku) {
		this.sku = sku;
	}
	
	private String action = "";
	public void setAction(String action) {
		this.action = action;
	}
	
	private String narrow = "";
	public void setNarrow(String narrow) {
		this.narrow = narrow;
	}

	//int[] SelectNumPage = {5, 10, 15};
	private int numproductperpage = 5;
	public void setNumproductperpage(int numproductperpage) {
		this.numproductperpage = numproductperpage;
	}

	private int numpage;
	public void setNumpage(int numpage) {
		this.numpage = numpage;
	}

	private int currentpage = 1;
	public void setCurrentpage(int currentpage) {
		this.currentpage = currentpage;
	}
	
	private int sortby = 1;
	public void setSortby(int sortby) {
		this.sortby = sortby;
	}


	public String execute()
	{
		
		
		if ( action.equals("AddToCart"))
		{
			Product product = ProductDAO.getProductBySKU(sku);
			if (product != null)
			{
				CartModel cartModel = (CartModel)session.get("cart");
				if (cartModel == null)
				{
					cartModel = new CartModel();
					cartModel.listProduct.add(new ProductCartDetail(product, 1));
					cartModel.price = cartModel.price.add(product.getPrice());
					cartModel.totalQuantity ++;
					session.put("cart", cartModel);
				}
				else
				{
					boolean flag = false;
					for ( int i = 0; i < cartModel.listProduct.size(); i++)
					{
						if ( cartModel.listProduct.get(i).productcart.getSku().equals(product.getSku()))
						{
							 ProductCartDetail pcd = cartModel.listProduct.get(i);
							 pcd.addQuantity(1);
							 cartModel.listProduct.set(i, pcd);
							cartModel.price = cartModel.price.add(product.getPrice());
							flag = true;
							break;
						}
					}
					if (flag == false)
					{
						cartModel.listProduct.add(new ProductCartDetail(product, 1));
						cartModel.price = cartModel.price.add(product.getPrice());
					}
					cartModel.totalQuantity ++;
					
				}
			}
		}
		else if ( action.equals("AddToWishList"))
		{
			
		}
		
		Category category = null;
		
		category = CategoryDAO.getCategoryFromId(idCategory);
		
		
		List<Price> lstPrice = null;
		List<DeviceBrand> lstDeviceBrand = null;
		List<Carrier> lstCarrier = null;
		List<OperatingSystem> lstOperatingSystem = null;
		List<CustomerReview> lstCustomerReview = null;
		if (narrow != null && narrow != "")
		{
			lstPrice = Tools.getInstance().findListPriceFromNarrow(narrow, "price~", PriceDAO);
			lstDeviceBrand = Tools.getInstance().findListDeviceBrandFromNarrow(narrow, "devicebrand~", DeviceBrandDAO);
			lstCarrier = Tools.getInstance().findListCarrierFromNarrow(narrow, "carrier~", CarrierDAO);
			lstOperatingSystem = Tools.getInstance().findListOSFromNarrow(narrow, "os~", OperatingSystemDAO);
			lstCustomerReview = Tools.getInstance().findListCustomerReviewFromNarrow(narrow, "rate~", CustomerReviewDAO);
		}
		
		if (category != null)
		{
			List<Product> _products = null;
			if (idCategory.equals("C1001"))
				_products = ProductDAO.getAllProduct(lstPrice, lstDeviceBrand, lstCarrier, lstOperatingSystem, lstCustomerReview);
			else
				_products = ProductDAO.getListProductFromIdCategory(idCategory, lstPrice, lstDeviceBrand, lstCarrier, lstOperatingSystem, lstCustomerReview);
			
			if (numproductperpage == -1)
				numpage = 1;
			else
			{
				numpage = _products.size() / numproductperpage;
				if (numpage * numproductperpage != _products.size())
				{
					numpage = numpage + 1;
				}
			}
			List<Integer> numpages = new ArrayList<Integer>();
			for ( int i = 1; i <= numpage; i++)
				numpages.add(i);
			
			
			List<ProductModel> products = new ArrayList<ProductModel>();
			
			if (idCategory.equals("C1001"))
			{
				_products = ProductDAO.getAllProduct(lstPrice, lstDeviceBrand, lstCarrier, lstOperatingSystem, lstCustomerReview, currentpage, numproductperpage, sortby);
				for (Product product : _products) {
					
					ProductModel productmodel = new ProductModel(product.getSku(),product.getCategory(), product.getIdProduct(), product.getModel(), product.getName(), product.getPrice(), product.isAvailable());
					if (product.getProductImages().iterator().hasNext())
						productmodel.productImages.add( ((ProductImage)product.getProductImages().iterator().next()));
					if (product.getOverviews().iterator().hasNext() )
					{
						Overview ov = (Overview)product.getOverviews().iterator().next();
						productmodel.features = Tools.getInstance().parseString(ov.getProductFeatures(), '~');
					}
					productmodel.rate = product.getRate();
					products.add(productmodel);
				}
			}
			else
			{
				_products = ProductDAO.getListProductFromIdCategory(idCategory, lstPrice, lstDeviceBrand, lstCarrier, lstOperatingSystem, lstCustomerReview, currentpage, numproductperpage, sortby);
				for (Product product : _products) {
					
					ProductModel productmodel = new ProductModel(product.getSku(),product.getCategory(), product.getIdProduct(), product.getModel(), product.getName(), product.getPrice(), product.isAvailable());
					if (product.getProductImages().iterator().hasNext())
						productmodel.productImages.add( ((ProductImage)product.getProductImages().iterator().next()));
					if (product.getOverviews().iterator().hasNext() )
					{
						Overview ov = (Overview)product.getOverviews().iterator().next();
						productmodel.features = Tools.getInstance().parseString(ov.getProductFeatures(), '~');
					}
					productmodel.rate = product.getRate();
					products.add(productmodel);
				}				
			}
			
			request.put("numpages", numpages);
			request.put("idCategory", idCategory);
			request.put("listproduct", products);
			request.put("TitleName", category.getName());
			request.put("narrow", narrow);
			request.put("sortby", sortby);
			request.put("numproductperpage", numproductperpage);
			request.put("currentpage", currentpage);
			
			return SUCCESS;
		}
		else if (idCategory.toLowerCase().equals("search") && keySearch != null)
		{
			List<Product> _products = null;
			_products = ProductDAO.getAllProductFromSearch(keySearch, lstPrice, lstDeviceBrand, lstCarrier, lstOperatingSystem, lstCustomerReview);
			
			if (numproductperpage == -1)
				numpage = 1;
			else
			{
				numpage = _products.size() / numproductperpage;
				if (numpage * numproductperpage != _products.size())
				{
					numpage = numpage + 1;
				}
			}
			List<Integer> numpages = new ArrayList<Integer>();
			for ( int i = 1; i <= numpage; i++)
				numpages.add(i);
			
			
			List<ProductModel> products = new ArrayList<ProductModel>();
			
			_products = ProductDAO.getAllProductFromSearch(keySearch, lstPrice, lstDeviceBrand, lstCarrier, lstOperatingSystem, lstCustomerReview, currentpage, numproductperpage, sortby);
			for (Product product : _products) {
				
				ProductModel productmodel = new ProductModel(product.getSku(),product.getCategory(), product.getIdProduct(), product.getModel(), product.getName(), product.getPrice(), product.isAvailable());
				if (product.getProductImages().iterator().hasNext())
					productmodel.productImages.add( ((ProductImage)product.getProductImages().iterator().next()));
				if (product.getOverviews().iterator().hasNext() )
				{
					Overview ov = (Overview)product.getOverviews().iterator().next();
					productmodel.features = Tools.getInstance().parseString(ov.getProductFeatures(), '~');
				}
				productmodel.rate = product.getRate();
				products.add(productmodel);
			}
			
			request.put("numpages", numpages);
			request.put("idCategory", idCategory);
			request.put("listproduct", products);
			request.put("TitleName", "Search " + keySearch);
			request.put("narrow", narrow);
			request.put("sortby", sortby);
			request.put("numproductperpage", numproductperpage);
			request.put("currentpage", currentpage);
			
			request.put("idCategory", idCategory);
			request.put("keySearch", keySearch);
			
			return SUCCESS;
		}
			
		return ERROR;
	}
	
	
	public void setIdCategory(String idCategory) {
		this.idCategory = idCategory;
	}
	
	public void setSession(Map<String, Object> arg0) {
		this.session = arg0;
	}

	public void setRequest(Map<String, Object> arg0) {
		this.request = arg0;
	}
	public String getKeySearch() {
		return keySearch;
	}
	public void setKeySearch(String keySearch) {
		this.keySearch = keySearch;
	}

}
